package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.MenuDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Menu;
import com.itheima.health.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Menu> queryMenuByRoleId(List<Long> roleIds) {
        List<Long> MenuIds = menuDao.selectMenuIdByRoleId(roleIds);
        List<Menu> fristMenuList = menuDao.selectFristByMenuIds(MenuIds);
        for (Menu menu : fristMenuList) {
            List<Menu> succendMenuList = menuDao.selectSuccendByMenuId(menu.getId(),MenuIds);
            menu.setChildren(succendMenuList);
        }
        return fristMenuList;
    }

    /**
     * 添加、编辑角色窗口页面菜单信息
     * @return
     */
    @Override
    public List<Menu> findMenu() {
        return menuDao.select();
    }
/**
 * @Author: Nic1
 * @Date: 2020/8/26 9:25
 * @Theme:
 */
    @Override
    public List<Menu> findFuMenuNameAndId() {
        return menuDao.selectMenuByLevel();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        log.info("[检查项-分页查询]data：{}",queryPageBean);
        //使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        // 分页查询数据库
        Page<Menu> page = menuDao.selectByConditon(queryPageBean.getQueryString());
        //封装分页数据
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void addMenu(Menu menu) {
        log.info("[添加菜单项]data:{}",menu);
        menuDao.addMenu(menu);
    }

    @Override
    public void editMenu(Menu menu) {
        log.info("[添加菜单项]data:{}",menu);
        menuDao.updateMenu(menu);
    }

    @Transactional
    @Override
    public void delete(Integer id) {
        log.info("[添加菜单项]data:{}",id);
        //删除自关联父菜单表
        //1.先查询是否有子菜单关联此id
        List<Menu> list = menuDao.selectHasSubMenu(id);
        if(list!=null){
            //有子菜单关联-先删除子菜单
            for (Menu menu : list) {
                menuDao.deleteRoleAndMenuByMenuId(menu.getId());
                menuDao.delete(menu.getId());
            }
        }
        //删除role_menu关联表
        menuDao.deleteRoleAndMenuByMenuId(id);
        //再删除选中菜单
        menuDao.delete(id);
    }
}
